package com.mgq.netty.nioselect;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author MaGuangQi
 * @description: 可写事件
 * @date 2021-12-03 15:44
 **/
public class WriteServer {

    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //只关注accept事件
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    StringBuilder s = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        s.append("a");
                    }
                    ByteBuffer byteBuffer = Charset.defaultCharset().encode(s.toString());
                    //返回写入的数量
                    int count = sc.write(byteBuffer);
                    System.out.println(count);
                    //buffer还有剩余,
                    if (byteBuffer.hasRemaining()) {
                        //有可能之前关注其他事件,不能把之前的事件替换,而是追加写事件
                        scKey.interestOps(scKey.interestOps()+SelectionKey.OP_WRITE);
                        //把没有写完的挂到scKey上.
                        scKey.attach(byteBuffer);
                    }
                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    //清理工作
                    if (!buffer.hasRemaining()) {
                        key.attach(null);
                        //去掉key的可写事件
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
